/*
Copyright 2009 Johan Maasing, Mikael Forsberg

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.code.pj2r.resources;

import javax.servlet.http.HttpServletRequest;

import com.google.code.pj2r.Marshaller;
import com.google.code.pj2r.MarshallingException;
import com.google.code.pj2r.Resource;
import com.google.code.pj2r.ResourceCreationException;
import com.google.code.pj2r.ResourceFactory;

public class RequestProcessor {

    private final ResourceFactory resourceFactory;
    private final Marshaller marshaller;

    public RequestProcessor(final ResourceFactory resourceFactory, final Marshaller marshaller) {
        this.resourceFactory = resourceFactory;
        this.marshaller = marshaller;
    }

    public RequestProcessorResult processRequest(HttpServletRequest request) throws MarshallingException, ResourceCreationException {
        ParsedPath parsedPath = parse(request.getPathInfo());
        Resource resource = resourceFactory.getResource(parsedPath.getName());
        marshaller.marshal(request, resource);
        RequestProcessorResult result = new RequestProcessorResult(parsedPath, resource);
        return result;
    }

    /**
     * Splits the requested path by slashes
     * TODO: How to handle subresources?
     *
     * @param The requested path. May not be null.
     * @throws IllegalArgumentException if pathInfo is null
     * @return ParsedPath object containing name, id (if any) and the rest of the url (if any).
     */
    private ParsedPath parse(final String pathInfo) {
        if (pathInfo == null) {
            throw new IllegalArgumentException("path info can't be null");
        }

        final String[] parts = pathInfo.split("/");
        ParsedPath parsedPath = null;
        if (parts.length >= 2) {
            final String resourceName = parts[1];
            final String subResourceID = (parts.length < 3) ? null : parts[2];
            parsedPath = new ParsedPath(resourceName, subResourceID, getRemainder(parts));
        }

        return parsedPath;
    }

    private String[] getRemainder(String[] parts) {
        if (parts.length > 3) {
            String[] remainder = new String[parts.length - 3];
            System.arraycopy(parts, 3, remainder, 0, parts.length - 3);
            return remainder;
        } else {
            return null;
        }
    }
}
